import type { GlobalThemeOverrides } from 'naive-ui';
import { themeSettings, overrideThemeSettings } from '@/theme/settings';
import { localStg } from '@/utils/storage';
import { getColorByColorPaletteNumber } from '@hl/color-palette';
import { addColorAlpha } from '@hl/utils';
import OtherTheme from '@/theme/naive-ui-theme-overrides.json';

/** 初始化主题设置 */
export function initThemeSettings() {
    const isProd = import.meta.env.PROD;

    /**
     * 如果是开发模式，主题设置将不会被缓存，通过更新 `src/theme/settings.ts` 中的 `themeSettings` 来更新主题设置
     */
    if (!isProd) return themeSettings;

    /**
     * 如果是生产模式，主题设置将会被缓存在 localStorage 中
     */
    const settings = localStg.get('themeSettings') || themeSettings;

    const isOverride = localStg.get('overrideThemeFlag') === BUILD_TIME;

    if (!isOverride) {
        Object.assign(settings, overrideThemeSettings); // 将 `overrideThemeSettings` 中的属性合并到 `settings` 中
        localStg.set('overrideThemeFlag', BUILD_TIME);
    }

    return settings;
}

type NaiveColorScene = '' | 'Suppl' | 'Hover' | 'Pressed' | 'Active';
type NaiveColorKey = `${App.Theme.ThemeColorKey}Color${NaiveColorScene}`;
type NaiveThemeColor = Partial<Record<NaiveColorKey, string>>;
interface NaiveColorAction {
    scene: NaiveColorScene;
    handler: (color: string) => string;
}

const getNaiveThemeColors = (colors: App.Theme.ThemeColor) => {
    const colorActions: NaiveColorAction[] = [
        { scene: '', handler: color => color },
        { scene: 'Suppl', handler: color => color },
        { scene: 'Hover', handler: color => getColorByColorPaletteNumber(color, 500) },
        { scene: 'Pressed', handler: color => getColorByColorPaletteNumber(color, 700) },
        { scene: 'Active', handler: color => addColorAlpha(color, 0.1) }
    ];

    const themeColors: NaiveThemeColor = {};
    const colorEntries = Object.entries(colors) as [App.Theme.ThemeColorKey, string][];
    colorEntries.forEach(color => {
        colorActions.forEach(action => {
            const [colorType, colorValue] = color;
            const colorKey: NaiveColorKey = `${colorType}Color${action.scene}`;
            themeColors[colorKey] = action.handler(colorValue);
        })
    })
    return themeColors;
}

/** 获取 Naive 主题 */
export function getNaiveTheme(colors: App.Theme.ThemeColor) {
    // 这里是结构赋值重命名 `primary` 为 `colorLoading`
    const { primary: colorLoading } = colors;
    const theme: GlobalThemeOverrides = {
        common: {
            ...getNaiveThemeColors(colors)
        },
        LoadingBar: {
            colorLoading
        },
        ...OtherTheme
    };
    return theme;
}
